﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "DrawingTableInteractionEventHandler.h"
#include "IInteractionEventArgs.h"
#include "ICommandInteractionEventArgs.h"
#include "IGenericElement.h"
#include "IDrawingTable.h"
#include "IDrawingTableItem.h"
#include "UiDocumentViewUtils.h"
#include "UiViewUtils.h"
#include "CommandParameters.h"
#include "IUiView.h"
#include "IUserTransaction.h"
#include "InteractionEventHandlerRegisterHelper.h"
#include "IUiViewMouseEventArgs.h"
#include "IUiViewMouseEvent.h"

#include <QWidget>
#include <QLineEdit>
#include <QKeyEvent>

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

TextEditor::TextEditor(QWidget* pParent)
    : QLineEdit(pParent), m_itemId(-1)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pParent, L"创建TextEditor给定的parent不能为空",L"GDMPLab",L"2024-03-30");
    pParent->installEventFilter(this);
}

bool gcmp::TextEditor::eventFilter(QObject * obj, QEvent * pEvent)
{
    if (pEvent->type() == QEvent::KeyPress && isVisible())
    {
        QKeyEvent* pKeyEvent = dynamic_cast<QKeyEvent*>(pEvent);
        if (pKeyEvent)
        {
            IUiView* pCurrentUiView = UiDocumentViewUtils::GetCurrentUiView();
            DBG_WARN_AND_RETURN_FALSE_UNLESS(pCurrentUiView, L"pCurrentUiView为空",L"GDMPLab",L"2024-03-30");
            QWidget* pWidget = QWidget::find((WId)(pCurrentUiView->GetUiViewId()));
            DBG_WARN_AND_RETURN_FALSE_UNLESS(pWidget, L"pCurrentUiView转化为QWidget失败",L"GDMPLab",L"2024-03-30");

            switch (pKeyEvent->key())
            {
            case Qt::Key_Return:// 日志敏感
            case Qt::Key_Enter:// 日志敏感
            {
                CloseTextEditor();
            }

            case Qt::Key_Escape:
            {
                clearFocus();
                hide();
            }

            default:
                break;
           } 
       } 
    }

    return QObject::eventFilter(obj, pEvent);
}

void gcmp::TextEditor::On(IUiViewMouseEventArgs * pArgs)
{
    IUiView* pCurrentUiView = UiDocumentViewUtils::GetCurrentUiView();
    if (pCurrentUiView && isVisible())
    {
        switch (pArgs->GetType())
        {
        case UiViewMouseEventType::Wheel:
        {
            IDocument* pDocument = UiDocumentViewUtils::GetCurrentDocument();
            DBG_WARN_AND_RETURN_VOID_UNLESS(pDocument, L"pDocument为空",L"GDMPLab",L"2024-03-30");
            IGenericElement* pElement = quick_cast<IGenericElement>(pDocument->GetElement(m_itemId));
            DBG_WARN_AND_RETURN_VOID_UNLESS(pElement, L"pElement为空",L"GDMPLab",L"2024-03-30");
            IDrawingTableItem* pTableItem = quick_cast<IDrawingTableItem>(pElement->GetExternalObject());
            DBG_WARN_AND_RETURN_VOID_UNLESS(pTableItem, L"pTableItem为空",L"GDMPLab",L"2024-03-30");
            ComputeTextEditorGeometry(pCurrentUiView, pTableItem);
            break;
        }

        case UiViewMouseEventType::LeftButtonDown:
        case UiViewMouseEventType::RightButtonDown:
        case UiViewMouseEventType::MiddleButtonDown:
            CloseTextEditor();
            break;
        default:
            break;
        }
    }
}

bool gcmp::TextEditor::SetDrawingTableItemId(ElementId id)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(id.IsValid(), L"无效ElementId",L"GDMPLab",L"2024-03-30");
    m_itemId = id;
    return true;
}

void gcmp::TextEditor::CloseTextEditor()
{
    IDocument* pDocument = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_VOID_UNLESS(pDocument, L"pDocument为空",L"GDMPLab",L"2024-03-30");
    IGenericElement* pElement = quick_cast<IGenericElement>(pDocument->GetElement(m_itemId));
    DBG_WARN_AND_RETURN_VOID_UNLESS(pElement, L"pElement为空",L"GDMPLab",L"2024-03-30");
    IDrawingTableItem* pTableItem = quick_cast<IDrawingTableItem>(pElement->GetExternalObject());
    DBG_WARN_AND_RETURN_VOID_UNLESS(pTableItem, L"pTableItem为空",L"GDMPLab",L"2024-03-30");

    OwnerPtr<IUserTransaction> opUt = IUserTransaction::Create(pElement->GetDocument(), L"修改表格item数据");
    pTableItem->SetText(this->text().toStdWString());
    clearFocus();
    hide();
    if(opUt)
        opUt->Commit();
}

void gcmp::TextEditor::ComputeTextEditorGeometry(IUiView* pCurrentUiView,IDrawingTableItem* pTableItem)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pCurrentUiView, L"pCurrentUiView为空",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_VOID_UNLESS(pTableItem, L"pTableItem为空",L"GDMPLab",L"2024-03-30");

    IDocument* pDocument = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_VOID_UNLESS(pDocument, L"pDocument为空",L"GDMPLab",L"2024-03-30");
    IGenericElement* pElement = quick_cast<IGenericElement>(pDocument->GetElement(pTableItem->GetDrawingTableElementId()));
    DBG_WARN_AND_RETURN_VOID_UNLESS(pElement, L"pElement为空",L"GDMPLab",L"2024-03-30");
    IDrawingTable* pTableElement = quick_cast<IDrawingTable>(pElement->GetExternalObject());
    DBG_WARN_AND_RETURN_VOID_UNLESS(pTableElement, L"pTableElement为空",L"GDMPLab",L"2024-03-30");

    double dScale = pTableItem->GetScale();
    double itemWidth = pTableItem->GetRealWidth() * dScale;
    double itemHeight = pTableItem->GetRealHeight() * dScale;
    Vector3d itemLeftTopPt = pTableItem->GetPosition();
    Coordinate3d coord = pTableElement->GetCoordinate3d();
    Matrix4d localMatrix;
    Vector3d localLeftTopPt = coord.GetLocalPoint(itemLeftTopPt);
    Vector3d localRightUpPt = Vector3d(localLeftTopPt.X() + itemWidth, localLeftTopPt.Y() - itemHeight, itemLeftTopPt.Z());
    Vector3d itemRightBottomPt = coord.GetWorldPoint(localRightUpPt);
    int ltScreenX = 0, ltscreenY = 0;
    int rbScreenX = 0, rbScreenY = 0;
    float depth = 0.0f;
    UiViewUtility::WorldPositionToScreenPosition(pCurrentUiView, itemLeftTopPt, ltScreenX, ltscreenY, depth);
    UiViewUtility::WorldPositionToScreenPosition(pCurrentUiView, itemRightBottomPt, rbScreenX, rbScreenY, depth);
    setGeometry(QRect(ltScreenX, ltscreenY, abs(rbScreenX - ltScreenX), abs(ltscreenY - rbScreenY)));
}

gcmp::DrawingTableInteractionEventHandler::DrawingTableInteractionEventHandler()
    :m_pLineEdit(nullptr)
{

}

gcmp::DrawingTableInteractionEventHandler::~DrawingTableInteractionEventHandler()
{
    if (m_pLineEdit)
        m_pLineEdit = nullptr;
}

void gcmp::DrawingTableInteractionEventHandler::On(IInteractionEventArgs* pArgs)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pArgs, L"args is null.",L"GDMPLab",L"2024-03-30");
    ICommandInteractionEventArgs* pCmdArgs = quick_cast<ICommandInteractionEventArgs>(pArgs);
    DBG_WARN_AND_RETURN_VOID_UNLESS(pCmdArgs, L"cmd args is null.",L"GDMPLab",L"2024-03-30");
    if (pCmdArgs->GetClickType() != ClickType::DoubleClick)
    {
        return;
    }

    IUiView* pCurrentUiView = UiDocumentViewUtils::GetCurrentUiView();
    DBG_WARN_AND_RETURN_VOID_UNLESS(pCurrentUiView, L"pCurrentUiView为空",L"GDMPLab",L"2024-03-30");
    QWidget* pWidget = QWidget::find((WId)(pCurrentUiView->GetUiViewId()));
    DBG_WARN_AND_RETURN_VOID_UNLESS(pWidget, L"pCurrentUiView转化为QWidget失败",L"GDMPLab",L"2024-03-30");

    //从CommandParameters中读取鼠标的世界坐标值
    Vector3d pos;
    CommandParameters cmdParams = pCmdArgs->GetCommandParameters();
    {
        auto itor = cmdParams.find(L"Vector3d_X");
        if (itor != cmdParams.end())
            pos.X() = itor->second.AsDouble();
    }

    {
        auto itor = cmdParams.find(L"Vector3d_Y");
        if (itor != cmdParams.end())
            pos.Y() = itor->second.AsDouble();
    }

    {
        auto itor = cmdParams.find(L"Vector3d_Z");
        if (itor != cmdParams.end())
            pos.Z() = itor->second.AsDouble();
    }

    IGenericElement* pElement = quick_cast<IGenericElement>(pCmdArgs->GetElement());
    if (!pElement)
        return;
    IDrawingTable* pTableElement = quick_cast<IDrawingTable>(pElement->GetExternalObject());
    if (!pTableElement)
        return;
    const TableItemIndex tableItemindex = pTableElement->GetItemIndexByPosition(pos);
    const IDrawingTableItem* pTableItem = pTableElement->GetTableItem(tableItemindex);
    if (!pTableItem)
        return;

    //单元格只读或者不可见，不可以双击编辑
    if (pTableItem->IsTextReadOnly() || pTableItem->IsTextVisibility() == false)
        return;

    std::wstring itemText = pTableItem->GetText();
    IDrawingTableItem* pItem = const_cast<IDrawingTableItem*>(pTableItem);
    DBG_WARN_AND_RETURN_VOID_UNLESS(pItem, L"TableItem const_cast转换失败",L"GDMPLab",L"2024-03-30");

    //每次双击需要重新创建一个TextEditor，否则上一次在某个视图双击之后的Editor，其所属的parent已经固定，会出现跳转的现象。
    m_pLineEdit = NEW_AS_QT(TextEditor, pWidget);
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_pLineEdit, L"m_pLineEdit为空",L"GDMPLab",L"2024-03-30");
    m_pLineEdit->setText(QString::fromStdWString(itemText));
    const IGenericElement* pTableItemEle = quick_cast<IGenericElement>(pTableItem->GetOwnerElement());
    DBG_WARN_AND_RETURN_VOID_UNLESS(pTableItemEle, L"pElement为空",L"GDMPLab",L"2024-03-30");
    m_pLineEdit->SetDrawingTableItemId(pTableItemEle->GetElementId());
    m_pLineEdit->ComputeTextEditorGeometry(pCurrentUiView, pItem);
    m_pLineEdit->show();
    m_pLineEdit->setFocus();
    if (IUiViewMouseEvent* pViewMouseEvent = pCurrentUiView->GetUiViewMouseEvent())
    {
        pViewMouseEvent->Add(m_pLineEdit);
    }

    pCmdArgs->SetExcuted(true);
}

REGISTER_INTERACTION_EVENT_HANDLER(IDrawingTable, DrawingTableInteractionEventHandler,
    ICommandInteractionEventArgs)
